<template>
  <view class="container">
    <!-- 页面标题 -->
    <view class="header">
      <text class="title">领取优惠券</text>
      <text class="subtitle">精选优惠券，限时领取</text>
    </view>
    
    <!-- 优惠券列表 -->
    <scroll-view 
      scroll-y 
      class="coupon-list"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view v-if="coupons.length > 0">
        <view 
          class="coupon-item" 
          v-for="coupon in coupons" 
          :key="coupon.id"
        >
          <view class="coupon-left">
            <text class="coupon-amount" v-if="coupon.type === 1">¥{{ coupon.value }}</text>
            <text class="coupon-amount" v-else-if="coupon.type === 2">{{ (coupon.value * 10).toFixed(1) }}折</text>
            <text class="coupon-condition">满{{ coupon.minConsume }}可用</text>
          </view>
          <view class="coupon-right">
            <text class="coupon-name">{{ coupon.name }}</text>
            <text class="coupon-time">{{ formatTime(coupon.receiveStartTime) }} - {{ formatTime(coupon.receiveEndTime) }}</text>
            <text class="coupon-desc">{{ coupon.description }}</text>
            <view class="coupon-footer">
              <text class="coupon-remain">剩余{{ coupon.remain }}张</text>
              <button 
                class="receive-btn" 
                @click="handleReceive(coupon)"
                :disabled="receiving === coupon.id"
              >
                {{ receiving === coupon.id ? '领取中...' : '立即领取' }}
              </button>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-else class="empty-state">
        <image class="empty-icon" src="/static/icons/empty-coupon.svg" mode="aspectFit"></image>
        <text class="empty-text">暂无可领取的优惠券</text>
        <text class="empty-desc">请关注最新活动信息</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getReceivableCoupons, receiveCoupon } from '@/api/coupon.js'

const coupons = ref([])
const refreshing = ref(false)
const receiving = ref(null) // 正在领取的优惠券ID

/**
 * 格式化时间
 */
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

/**
 * 加载可领取的优惠券列表
 */
const loadCoupons = async () => {
  try {
    const res = await getReceivableCoupons()
    coupons.value = res.data || []
  } catch (error) {
    console.error('获取可领取优惠券失败:', error)
    coupons.value = []
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
  }
}

/**
 * 领取优惠券
 */
const handleReceive = async (coupon) => {
  if (receiving.value) return
  
  receiving.value = coupon.id
  
  try {
    await receiveCoupon(coupon.id)
    
    uni.showToast({
      title: '领取成功',
      icon: 'success'
    })
    
    // 更新优惠券剩余数量
    coupon.remain = coupon.remain - 1
    
    // 如果剩余数量为0，从列表中移除
    if (coupon.remain <= 0) {
      const index = coupons.value.findIndex(item => item.id === coupon.id)
      if (index > -1) {
        coupons.value.splice(index, 1)
      }
    }
    
  } catch (error) {
    console.error('领取优惠券失败:', error)
    uni.showToast({
      title: error.message || '领取失败，请重试',
      icon: 'none'
    })
  } finally {
    receiving.value = null
  }
}

/**
 * 下拉刷新
 */
const onRefresh = async () => {
  refreshing.value = true
  await loadCoupons()
  refreshing.value = false
}

// 页面加载时获取数据
onMounted(() => {
  loadCoupons()
})
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  
  .title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 10rpx;
  }
  
  .subtitle {
    display: block;
    font-size: 28rpx;
    opacity: 0.9;
  }
}

.coupon-list {
  flex: 1;
  padding: 20rpx;
}

.coupon-item {
  display: flex;
  background: white;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.coupon-left {
  width: 200rpx;
  background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    right: -10rpx;
    top: 50%;
    transform: translateY(-50%);
    width: 20rpx;
    height: 20rpx;
    background: #f5f5f5;
    border-radius: 50%;
  }
  
  .coupon-amount {
    font-size: 48rpx;
    font-weight: bold;
    line-height: 1;
  }
  
  .coupon-condition {
    font-size: 24rpx;
    margin-top: 8rpx;
    opacity: 0.9;
  }
}

.coupon-right {
  flex: 1;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  
  .coupon-name {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 8rpx;
  }
  
  .coupon-time {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 8rpx;
  }
  
  .coupon-desc {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 20rpx;
    line-height: 1.4;
  }
  
  .coupon-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .coupon-remain {
      font-size: 24rpx;
      color: #ff6b6b;
    }
    
    .receive-btn {
      background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
      color: white;
      border: none;
      border-radius: 40rpx;
      padding: 12rpx 32rpx;
      font-size: 26rpx;
      
      &:disabled {
        background: #ccc;
        color: #999;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  
  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 40rpx;
    opacity: 0.6;
  }
  
  .empty-text {
    font-size: 32rpx;
    color: #999;
    margin-bottom: 16rpx;
  }
  
  .empty-desc {
    font-size: 28rpx;
    color: #ccc;
  }
}
</style>